<template>
  <div class="person">
    <h1>情况五：监视上述的多个数据</h1>
    <!--现在我想监视人的名字和第一台车-->
    <h2>姓名：{{ person.name }}</h2>
    <h2>年龄：{{ person.age }}</h2>
    <h2>车型：{{ person.car.c1 }},{{ person.car.c2 }}</h2>
    <button @click="changeName">修改姓名</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeBrand1">修改第一台车</button>
    <button @click="changeBrand2">修改第二台车</button>
    <button @click="changeBrand">修改所有车</button>
  </div>
</template>

<script setup name="Person">
import { reactive, watch } from "vue";

let person = reactive({
  name: "张三",
  age: 20,
  car: {
    c1: "奔驰",
    c2: "宝马",
  },
});

function changeName() {
  person.name += "~";
}

function changeAge() {
  person.age += 1;
}

function changeBrand1() {
  person.car.c1 = "劳斯莱斯";
}

function changeBrand2() {
  person.car.c2 = "迈巴赫";
}

function changeBrand() {
  person.car = { c1: "劳斯莱斯幻影", c2: "宾利" };
}

//这里不能让 watch 直接监视 person.name, 因为person.name是一个字符串，
//属于基础数据类型，watch 只能监视 ref, reactive, function, 或者这些类型组合起来的数组
/*错误写法：
watch(person.name, (value) => {
  console.log("person.name 变化为", value);
});
*/

//把 person.name 加工成 getter 函数，getter 函数，能返回一个值的函数
//监视，情况五：监视上述的多个数据
/*
watch(
  () => {
    return person.name;
  },
  (value) => {
    console.log("person.name 变化为", value);
  }
);
*/

//建议写函数式，直接写对象，监视的是原来的car，car更改后整个car没了，就监视不到了
watch([() => person.name, () => person.car.c1], (newValue, oldValue) => {
  console.log("person.car 变化了", newValue, oldValue);
});
</script>
<style scoped>
.person {
  background-color: #c2e0f6;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
button {
  margin: 0 5px;
}
</style>